/**
 * 需求详情页面JavaScript
 * 负责需求详情的展示、参考文档管理、状态流转等功能
 */

// 全局变量
let currentRequirement = null;
let currentDocuments = [];
let currentTasks = [];
let requirementId = null;

// DOM元素
const elements = {};

/**
 * 初始化DOM元素
 */
function initializeElements() {
    console.log('=== 开始初始化DOM元素 ===');
    
    // 基本信息
    elements.requirementTitle = document.getElementById('requirementTitle');
    elements.requirementStatus = document.getElementById('requirementStatus');
    elements.requirementPriority = document.getElementById('requirementPriority');
    elements.detailTitle = document.getElementById('detailTitle');
    elements.detailDescription = document.getElementById('detailDescription');
    elements.detailProject = document.getElementById('detailProject');
    elements.detailOwner = document.getElementById('detailOwner');
    elements.detailExpectedDate = document.getElementById('detailExpectedDate');
    elements.detailCreatedAt = document.getElementById('detailCreatedAt');
    elements.detailUpdatedAt = document.getElementById('detailUpdatedAt');
    
    // 文档相关
    elements.documentCount = document.getElementById('documentCount');
    elements.documentsList = document.getElementById('documentsList');
    elements.noDocuments = document.getElementById('noDocuments');
    elements.addDocumentBtn = document.getElementById('addDocumentBtn');
    elements.addDocumentModal = document.getElementById('addDocumentModal');
    elements.addDocumentForm = document.getElementById('addDocumentForm');
    elements.saveDocumentBtn = document.getElementById('saveDocumentBtn');
    
    // 任务相关
    elements.taskCount = document.getElementById('taskCount');
    elements.tasksList = document.getElementById('tasksList');
    elements.noTasks = document.getElementById('noTasks');
    elements.createTaskBtn = document.getElementById('createTaskBtn');
    
    // 操作按钮
    elements.editBtn = document.getElementById('editBtn');
    elements.exportBtn = document.getElementById('exportBtn');
    elements.approveBtn = document.getElementById('approveBtn');
    elements.rejectBtn = document.getElementById('rejectBtn');
    elements.assignOwnerBtn = document.getElementById('assignOwnerBtn');
    elements.changeStatusBtn = document.getElementById('changeStatusBtn');
    elements.setPriorityBtn = document.getElementById('setPriorityBtn');
    elements.duplicateBtn = document.getElementById('duplicateBtn');
    
    // 其他
    elements.operationHistory = document.getElementById('operationHistory');
    elements.loadingOverlay = document.getElementById('loadingOverlay');
    elements.successToast = document.getElementById('successToast');
    elements.errorToast = document.getElementById('errorToast');
    elements.successMessage = document.getElementById('successMessage');
    elements.errorMessage = document.getElementById('errorMessage');
    
    // 检查关键元素
    console.log('documentsList元素:', elements.documentsList);
    console.log('documentCount元素:', elements.documentCount);
    console.log('addDocumentBtn元素:', elements.addDocumentBtn);
    
    console.log('=== DOM元素初始化完成 ===');
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('=== 页面开始初始化 ===');
    
    console.log('初始化DOM元素...');
    initializeElements();
    
    console.log('初始化页面...');
    initializePage();
    
    console.log('绑定事件...');
    bindEvents();
    
    console.log('加载需求数据...');
    loadRequirementData();
    
    console.log('=== 页面初始化完成 ===');
});

/**
 * 初始化页面
 */
function initializePage() {
    // 从URL路径获取需求ID
    const pathParts = window.location.pathname.split('/');
    requirementId = pathParts[pathParts.length - 1];
    
    // 如果路径末尾不是数字，尝试从查询参数获取（兼容旧版本）
    if (!requirementId || isNaN(requirementId)) {
        const urlParams = new URLSearchParams(window.location.search);
        requirementId = urlParams.get('id');
    }
    
    if (!requirementId || isNaN(requirementId)) {
        showError('未指定需求ID或ID格式不正确');
        return;
    }
    
    // 初始化Bootstrap组件
    initializeBootstrapComponents();
}

/**
 * 初始化Bootstrap组件
 */
function initializeBootstrapComponents() {
    // 初始化模态框
    if (elements.addDocumentModal) {
        new bootstrap.Modal(elements.addDocumentModal);
    }
    
    // 初始化Toast
    if (elements.successToast) {
        new bootstrap.Toast(elements.successToast);
    }
    if (elements.errorToast) {
        new bootstrap.Toast(elements.errorToast);
    }
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 初始化文档相关事件
    initDocumentEvents();
    
    // 文档相关事件已在initDocumentEvents()中处理
    
    // 操作按钮事件
    if (elements.editBtn) {
        elements.editBtn.addEventListener('click', editRequirement);
    }
    if (elements.exportBtn) {
        elements.exportBtn.addEventListener('click', exportRequirement);
    }
    if (elements.approveBtn) {
        elements.approveBtn.addEventListener('click', approveRequirement);
    }
    if (elements.rejectBtn) {
        elements.rejectBtn.addEventListener('click', rejectRequirement);
    }
    if (elements.assignOwnerBtn) {
        elements.assignOwnerBtn.addEventListener('click', assignOwner);
    }
    if (elements.changeStatusBtn) {
        elements.changeStatusBtn.addEventListener('click', changeStatus);
    }
    if (elements.setPriorityBtn) {
        elements.setPriorityBtn.addEventListener('click', setPriority);
    }
    if (elements.duplicateBtn) {
        elements.duplicateBtn.addEventListener('click', duplicateRequirement);
    }
    if (elements.createTaskBtn) {
        elements.createTaskBtn.addEventListener('click', createTask);
    }
    
    // 表单提交事件
    if (elements.addDocumentForm) {
        elements.addDocumentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveDocument();
        });
    }
    
    // 分配负责人确认按钮事件
    const confirmAssignBtn = document.getElementById('confirmAssignBtn');
    if (confirmAssignBtn) {
        confirmAssignBtn.addEventListener('click', confirmAssignOwner);
    }
}

/**
 * 加载需求数据
 */
async function loadRequirementData() {
    try {
        showLoading(true);
        
        // 并行加载数据
        const [requirement, documents, tasks] = await Promise.all([
            loadRequirement(),
            loadDocuments(),
            loadTasks()
        ]);
        
        currentRequirement = requirement;
        currentDocuments = documents;
        currentTasks = tasks;
        
        // 渲染页面
        renderRequirementInfo();
        renderDocuments();
        renderTasks();
        renderStatusFlow();
        loadOperationHistory();
        
    } catch (error) {
        console.error('加载需求数据失败:', error);
        showError('加载需求数据失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

/**
 * 加载需求基本信息
 */
async function loadRequirement() {
    const response = await fetch(`/api/requirements/${requirementId}`);
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    return await response.json();
}

/**
 * 加载参考文档
 */
async function loadDocuments() {
    try {
        console.log('=== 开始加载文档 ===');
        console.log('需求ID:', requirementId);
        console.log('请求URL:', `/api/requirements/${requirementId}/documents`);
        
        const response = await fetch(`/api/requirements/${requirementId}/documents`);
        console.log('响应状态:', response.status, response.statusText);
        
        if (!response.ok) {
            if (response.status === 404) {
                console.log('文档不存在，返回空数组');
                return [];
            }
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const documents = await response.json();
        console.log('API返回的原始数据:', documents);
        console.log('数据类型:', typeof documents);
        console.log('是否为数组:', Array.isArray(documents));
        
        const result = Array.isArray(documents) ? documents : [];
        console.log('最终返回的文档数据:', result);
        console.log('文档数量:', result.length);
        console.log('=== 文档加载完成 ===');
        
        return result;
    } catch (error) {
        console.error('加载文档失败:', error);
        return [];
    }
}

/**
 * 加载关联任务
 */
async function loadTasks() {
    try {
        const response = await fetch(`/api/requirements/${requirementId}/tasks`);
        if (!response.ok) {
            if (response.status === 404) {
                return [];
            }
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.warn('加载任务失败:', error);
        return [];
    }
}

/**
 * 渲染需求基本信息
 */
function renderRequirementInfo() {
    if (!currentRequirement) return;
    
    const req = currentRequirement;
    
    // 更新页面标题
    if (elements.requirementTitle) {
        elements.requirementTitle.textContent = req.title || '未知需求';
    }
    
    // 更新状态标签
    if (elements.requirementStatus) {
        elements.requirementStatus.textContent = getStatusText(req.status);
        elements.requirementStatus.className = `badge requirement-status ${getStatusClass(req.status)}`;
    }
    
    // 更新优先级标签
    if (elements.requirementPriority) {
        elements.requirementPriority.textContent = getPriorityText(req.priority);
        elements.requirementPriority.className = `badge requirement-priority ${getPriorityClass(req.priority)}`;
    }
    
    // 更新详细信息
    if (elements.detailTitle) {
        elements.detailTitle.textContent = req.title || '无';
    }
    if (elements.detailDescription) {
        elements.detailDescription.textContent = req.description || '无描述';
    }
    if (elements.detailProject) {
        elements.detailProject.textContent = req.projectName || '未分配';
    }
    if (elements.detailOwner) {
        elements.detailOwner.textContent = req.ownerName || '未分配';
    }
    if (elements.detailExpectedDate) {
        elements.detailExpectedDate.textContent = req.expectedCompletionDate ? 
            formatDate(req.expectedCompletionDate) : '未设置';
    }
    if (elements.detailCreatedAt) {
        elements.detailCreatedAt.textContent = formatDateTime(req.createdAt);
    }
    if (elements.detailUpdatedAt) {
        elements.detailUpdatedAt.textContent = formatDateTime(req.updatedAt);
    }
    
    // 更新操作按钮状态
    updateActionButtons();
}

/**
 * 渲染参考文档列表
 */
function renderDocuments() {
    console.log('=== 开始渲染文档 ===');
    console.log('当前文档数据:', currentDocuments);
    console.log('文档数量:', currentDocuments ? currentDocuments.length : 0);
    
    updateDocumentsList();
    
    console.log('=== 文档渲染完成 ===');
}

/**
 * 更新文档列表显示
 */
function updateDocumentsList() {
    if (!elements.documentsList || !elements.documentCount) return;
    
    // 确保currentDocuments已初始化
    if (!currentDocuments) {
        currentDocuments = [];
    }
    
    // 更新文档数量
    elements.documentCount.textContent = currentDocuments.length;
    
    if (currentDocuments.length === 0) {
        // 显示空状态
        if (elements.noDocuments) {
            elements.documentsList.innerHTML = elements.noDocuments.outerHTML;
        }
    } else {
        // 显示文档列表
        const documentsHtml = currentDocuments.map(doc => {
            return createDocumentItem(doc);
        }).join('');
        elements.documentsList.innerHTML = documentsHtml;
        
        // 绑定删除按钮事件
        bindDocumentDeleteEvents();
    }
}
/**
 * 渲染任务列表
 */
function renderTasks() {
    if (!elements.tasksList || !elements.taskCount) return;
    
    // 更新任务数量
    elements.taskCount.textContent = currentTasks.length;
    
    if (currentTasks.length === 0) {
        // 显示空状态
        if (elements.noTasks) {
            elements.noTasks.style.display = 'block';
        }
        elements.tasksList.innerHTML = '';
        return;
    }
    
    // 隐藏空状态
    if (elements.noTasks) {
        elements.noTasks.style.display = 'none';
    }
    
    // 渲染任务列表
    const tasksHtml = currentTasks.map(task => createTaskHtml(task)).join('');
    elements.tasksList.innerHTML = tasksHtml;
}

/**
 * 创建任务HTML
 */
function createTaskHtml(task) {
    return `
        <div class="task-item fade-in" data-task-id="${task.id}">
            <div class="task-header">
                <h6 class="task-title">${escapeHtml(task.title)}</h6>
                <span class="task-status ${getTaskStatusClass(task.status)}">
                    ${getTaskStatusText(task.status)}
                </span>
            </div>
            <div class="task-meta">
                <div class="task-assignee">
                    <i class="bi bi-person"></i>
                    <span>${task.assigneeName || '未分配'}</span>
                </div>
                <span>截止: ${task.deadline ? formatDate(task.deadline) : '未设置'}</span>
            </div>
        </div>
    `;
}

/**
 * 渲染状态流转
 */
function renderStatusFlow() {
    if (!currentRequirement) return;
    
    const statusSteps = document.querySelectorAll('.status-step');
    const currentStatus = currentRequirement.status;
    
    statusSteps.forEach(step => {
        const stepStatus = step.getAttribute('data-status');
        step.classList.remove('active', 'completed');
        
        if (stepStatus === currentStatus) {
            step.classList.add('active');
        } else if (isStatusCompleted(stepStatus, currentStatus)) {
            step.classList.add('completed');
        }
    });
}

/**
 * 加载操作历史
 */
async function loadOperationHistory() {
    try {
        const response = await fetch(`/api/requirements/${requirementId}/history`);
        if (!response.ok) {
            if (response.status === 404) {
                renderEmptyHistory();
                return;
            }
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const history = await response.json();
        renderOperationHistory(history);
        
    } catch (error) {
        console.warn('加载操作历史失败:', error);
        renderEmptyHistory();
    }
}

/**
 * 渲染操作历史
 */
function renderOperationHistory(history) {
    if (!elements.operationHistory) return;
    
    if (!history || history.length === 0) {
        renderEmptyHistory();
        return;
    }
    
    const historyHtml = history.map(item => createHistoryHtml(item)).join('');
    elements.operationHistory.innerHTML = historyHtml;
}

/**
 * 渲染空历史状态
 */
function renderEmptyHistory() {
    if (!elements.operationHistory) return;
    
    elements.operationHistory.innerHTML = `
        <div class="text-center text-muted py-3">
            <i class="bi bi-clock-history" style="font-size: 2rem;"></i>
            <p class="mt-2 mb-0">暂无操作记录</p>
        </div>
    `;
}

/**
 * 创建历史记录HTML
 */
function createHistoryHtml(item) {
    return `
        <div class="history-item ${getHistoryTypeClass(item.type)} slide-in">
            <div class="history-action">${escapeHtml(item.action)}</div>
            <div class="history-details">${escapeHtml(item.details)}</div>
            <div class="history-time">${formatDateTime(item.createdAt)}</div>
        </div>
    `;
}

// 重复函数已移除，使用后面更完整的版本

// 重复函数已移除，使用后面更完整的版本

// 重复函数已移除，使用后面更完整的版本

// 重复函数已移除，使用后面更完整的版本

// 重复函数已移除，使用后面更完整的版本

/**
 * 编辑文档
 */
function editDocument(documentId) {
    // TODO: 实现编辑文档功能
    console.log('编辑文档:', documentId);
    showInfo('编辑文档功能开发中...');
}

// 重复函数已移除，使用后面更完整的版本

/**
 * 更新操作按钮状态
 */
function updateActionButtons() {
    if (!currentRequirement) return;
    
    const status = currentRequirement.status;
    
    // 根据状态启用/禁用按钮
    if (elements.approveBtn) {
        elements.approveBtn.disabled = status !== 'ANALYSIS';
    }
    if (elements.rejectBtn) {
        elements.rejectBtn.disabled = status === 'COMPLETED' || status === 'CANCELLED';
    }
}

// 操作按钮事件处理函数
function editRequirement() {
    window.location.href = `/requirements/${requirementId}/edit`;
}

function exportRequirement() {
    // TODO: 实现导出功能
    showInfo('导出功能开发中...');
}

async function approveRequirement() {
    await updateRequirementStatus('APPROVED');
}

async function rejectRequirement() {
    await updateRequirementStatus('REJECTED');
}

async function assignOwner() {
    try {
        // 加载可分配的开发者列表
        await loadAssignableDevelopers();
        
        // 显示分配负责人弹窗
        const modal = new bootstrap.Modal(document.getElementById('assignOwnerModal'));
        modal.show();
    } catch (error) {
        console.error('打开分配负责人弹窗失败:', error);
        showError('加载开发者列表失败，请重试');
    }
}

function changeStatus() {
    // TODO: 实现状态变更功能
    showInfo('状态变更功能开发中...');
}

function setPriority() {
    // TODO: 实现优先级设置功能
    showInfo('优先级设置功能开发中...');
}

function duplicateRequirement() {
    // TODO: 实现复制需求功能
    showInfo('复制需求功能开发中...');
}

function createTask() {
    // TODO: 实现创建任务功能
    showInfo('创建任务功能开发中...');
}

/**
 * 更新需求状态
 */
async function updateRequirementStatus(newStatus) {
    try {
        showLoading(true);
        
        const response = await fetch(`/api/requirements/${requirementId}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ status: newStatus })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        // 重新加载需求数据
        await loadRequirementData();
        
        showSuccess(`需求状态已更新为: ${getStatusText(newStatus)}`);
        
    } catch (error) {
        console.error('更新状态失败:', error);
        showError('更新状态失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 工具函数
function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'ANALYSIS': '分析中',
        'APPROVED': '已批准',
        'IN_DEVELOPMENT': '开发中',
        'COMPLETED': '已完成',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
}

function getStatusClass(status) {
    const classMap = {
        'DRAFT': 'status-draft',
        'ANALYSIS': 'status-analysis',
        'APPROVED': 'status-approved',
        'IN_DEVELOPMENT': 'status-in-development',
        'COMPLETED': 'status-completed',
        'REJECTED': 'status-rejected',
        'CANCELLED': 'status-cancelled'
    };
    return classMap[status] || 'status-draft';
}

function getPriorityText(priority) {
    const priorityMap = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
    };
    return priorityMap[priority] || priority;
}

function getPriorityClass(priority) {
    const classMap = {
        'LOW': 'priority-low',
        'MEDIUM': 'priority-medium',
        'HIGH': 'priority-high',
        'URGENT': 'priority-urgent'
    };
    return classMap[priority] || 'priority-medium';
}



function getTaskStatusText(status) {
    const statusMap = {
        'TODO': '待办',
        'IN_PROGRESS': '进行中',
        'DONE': '已完成'
    };
    return statusMap[status] || status;
}

function getTaskStatusClass(status) {
    const classMap = {
        'TODO': 'status-todo',
        'IN_PROGRESS': 'status-in-progress',
        'DONE': 'status-done'
    };
    return classMap[status] || 'status-todo';
}

function getHistoryTypeClass(type) {
    const classMap = {
        'CREATE': 'type-create',
        'UPDATE': 'type-update',
        'STATUS_CHANGE': 'type-status',
        'ASSIGN': 'type-assign'
    };
    return classMap[type] || 'type-update';
}

function isStatusCompleted(stepStatus, currentStatus) {
    const statusOrder = ['DRAFT', 'ANALYSIS', 'APPROVED', 'IN_DEVELOPMENT', 'COMPLETED'];
    const stepIndex = statusOrder.indexOf(stepStatus);
    const currentIndex = statusOrder.indexOf(currentStatus);
    return stepIndex < currentIndex;
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function formatDateTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

function showLoading(show) {
    if (!elements.loadingOverlay) return;
    
    if (show) {
        elements.loadingOverlay.classList.remove('d-none');
    } else {
        elements.loadingOverlay.classList.add('d-none');
    }
}

function showSuccess(message) {
    if (!elements.successToast || !elements.successMessage) return;
    
    elements.successMessage.textContent = message;
    const toast = bootstrap.Toast.getInstance(elements.successToast) || 
                  new bootstrap.Toast(elements.successToast);
    toast.show();
}

function showError(message) {
    if (!elements.errorToast || !elements.errorMessage) return;
    
    elements.errorMessage.textContent = message;
    const toast = bootstrap.Toast.getInstance(elements.errorToast) || 
                  new bootstrap.Toast(elements.errorToast);
    toast.show();
}

function showInfo(message) {
    // 使用成功Toast显示信息
    showSuccess(message);
}

// ==================== 文档管理功能 ====================

/**
 * 初始化文档相关事件监听器
 */
function initDocumentEvents() {
    // 添加文档按钮点击事件
    if (elements.addDocumentBtn) {
        elements.addDocumentBtn.addEventListener('click', function() {
            showAddDocumentModal();
        });
    }
    
    // 保存文档按钮点击事件
    if (elements.saveDocumentBtn) {
        elements.saveDocumentBtn.addEventListener('click', function() {
            saveDocument();
        });
    }
    
    // 模态框关闭时重置表单
    if (elements.addDocumentModal) {
        elements.addDocumentModal.addEventListener('hidden.bs.modal', function() {
            resetDocumentForm();
        });
    }
}

/**
 * 显示添加文档模态框
 */
function showAddDocumentModal() {
    if (!elements.addDocumentModal) return;
    
    resetDocumentForm();
    const modal = bootstrap.Modal.getInstance(elements.addDocumentModal) || 
                  new bootstrap.Modal(elements.addDocumentModal);
    modal.show();
}

/**
 * 重置文档表单
 */
function resetDocumentForm() {
    if (!elements.addDocumentForm) return;
    
    elements.addDocumentForm.reset();
    // 移除验证样式
    const inputs = elements.addDocumentForm.querySelectorAll('.form-control');
    inputs.forEach(input => {
        input.classList.remove('is-valid', 'is-invalid');
    });
}

/**
 * 保存文档
 */
async function saveDocument() {
    if (!validateDocumentForm()) {
        return;
    }
    
    const formData = getDocumentFormData();
    if (!formData) return;
    
    try {
        elements.saveDocumentBtn.disabled = true;
        elements.saveDocumentBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
        
        const response = await fetch(`/api/requirements/${requirementId}/documents`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        if (response.ok) {
            const document = await response.json();
            if (!currentDocuments) {
                currentDocuments = [];
            }
            currentDocuments.push(document);
            updateDocumentsList();
            hideAddDocumentModal();
            showSuccess('文档添加成功！');
        } else {
            const errorText = await response.text();
            showError(errorText || '添加文档失败，请重试');
        }
    } catch (error) {
        console.error('添加文档失败:', error);
        showError('网络错误，请检查网络连接后重试');
    } finally {
        elements.saveDocumentBtn.disabled = false;
        elements.saveDocumentBtn.innerHTML = '<i class="bi bi-check"></i> 保存';
    }
}

/**
 * 验证文档表单
 */
function validateDocumentForm() {
    if (!elements.addDocumentForm) return false;
    
    const titleInput = document.getElementById('documentTitle');
    const urlInput = document.getElementById('documentUrl');
    
    let isValid = true;
    
    // 验证标题
    if (!titleInput.value.trim()) {
        titleInput.classList.add('is-invalid');
        isValid = false;
    } else {
        titleInput.classList.remove('is-invalid');
        titleInput.classList.add('is-valid');
    }
    
    // 验证URL
    if (!urlInput.value.trim() || !isValidUrl(urlInput.value.trim())) {
        urlInput.classList.add('is-invalid');
        isValid = false;
    } else {
        urlInput.classList.remove('is-invalid');
        urlInput.classList.add('is-valid');
    }
    
    return isValid;
}

/**
 * 获取文档表单数据
 */
function getDocumentFormData() {
    const titleInput = document.getElementById('documentTitle');
    const urlInput = document.getElementById('documentUrl');
    const descriptionInput = document.getElementById('documentDescription');
    
    if (!titleInput || !urlInput) return null;
    
    return {
        title: titleInput.value.trim(),
        url: urlInput.value.trim(),
        description: descriptionInput ? descriptionInput.value.trim() : ''
    };
}

/**
 * 隐藏添加文档模态框
 */
function hideAddDocumentModal() {
    if (!elements.addDocumentModal) return;
    
    const modal = bootstrap.Modal.getInstance(elements.addDocumentModal);
    if (modal) {
        modal.hide();
    }
}

// 重复的函数定义已移除，使用上面的版本

/**
 * 创建文档项HTML
 */
function createDocumentItem(document) {
    try {
        const createdAt = formatDate(new Date(document.createdAt));
        const description = document.description ? escapeHtml(document.description) : '无描述';
        
        const html = `
            <div class="document-item border rounded p-3 mb-3" data-document-id="${document.documentId}">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h6 class="mb-2">
                            <i class="bi bi-file-earmark-text text-primary me-2"></i>
                            <a href="${escapeHtml(document.url)}" target="_blank" class="text-decoration-none">
                                ${escapeHtml(document.title)}
                            </a>
                        </h6>
                        <p class="text-muted mb-2 small">${description}</p>
                        <small class="text-muted">
                            <i class="bi bi-clock me-1"></i>
                            添加于 ${createdAt}
                        </small>
                    </div>
                    <div class="ms-3">
                        <button type="button" class="btn btn-sm btn-outline-danger delete-document-btn" 
                                data-document-id="${document.documentId}" title="删除文档">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        return html;
    } catch (error) {
        console.error('createDocumentItem出错:', error);
        return '<div class="alert alert-danger">文档渲染出错</div>';
    }
}

/**
 * 绑定文档删除事件
 */
function bindDocumentDeleteEvents() {
    const deleteButtons = document.querySelectorAll('.delete-document-btn');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const documentId = this.getAttribute('data-document-id');
            if (documentId) {
                deleteDocument(documentId);
            }
        });
    });
}

/**
 * 删除文档
 */
async function deleteDocument(documentId) {
    if (!confirm('确定要删除这个文档吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/requirements/${requirementId}/documents/${documentId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            // 从当前文档列表中移除
            currentDocuments = currentDocuments.filter(doc => doc.documentId.toString() !== documentId.toString());
            updateDocumentsList();
            showSuccess('文档删除成功！');
        } else {
            const errorText = await response.text();
            showError(errorText || '删除文档失败，请重试');
        }
    } catch (error) {
        console.error('删除文档失败:', error);
        showError('网络错误，请检查网络连接后重试');
    }
}

/**
 * 加载可分配的开发者列表
 */
async function loadAssignableDevelopers() {
    try {
        const response = await fetch('/api/developers/assignable');
        if (!response.ok) {
            throw new Error('获取开发者列表失败');
        }
        
        const developers = await response.json();
        const ownerSelect = document.getElementById('ownerSelect');
        
        // 清空现有选项（保留默认选项）
        ownerSelect.innerHTML = '<option value="">请选择负责人</option>';
        
        // 添加开发者选项
        developers.forEach(developer => {
            const option = document.createElement('option');
            option.value = developer.id;
            option.textContent = `${developer.name} (${developer.id}) - ${developer.role}`;
            ownerSelect.appendChild(option);
        });
        
        console.log('加载了', developers.length, '个可分配的开发者');
    } catch (error) {
        console.error('加载开发者列表失败:', error);
        throw error;
    }
}

/**
 * 确认分配负责人
 */
async function confirmAssignOwner() {
    const ownerSelect = document.getElementById('ownerSelect');
    const assignReason = document.getElementById('assignReason');
    
    const ownerId = ownerSelect.value;
    if (!ownerId) {
        showError('请选择负责人');
        return;
    }
    
    try {
        showLoading(true);
        
        const response = await fetch(`/api/requirements/${requirementId}/assign`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `ownerId=${encodeURIComponent(ownerId)}`
        });
        
        if (response.ok) {
            // 关闭弹窗
            const modal = bootstrap.Modal.getInstance(document.getElementById('assignOwnerModal'));
            modal.hide();
            
            // 重新加载需求数据以更新显示
            await loadRequirementData();
            
            showSuccess('负责人分配成功');
            
            // 清空表单
            ownerSelect.value = '';
            assignReason.value = '';
        } else {
            const errorText = await response.text();
            showError(errorText || '分配负责人失败');
        }
    } catch (error) {
        console.error('分配负责人失败:', error);
        showError('分配负责人失败，请重试');
    } finally {
        showLoading(false);
    }
}